package com.campus.counseling.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.campus.counseling.entity.Counselor;
import com.campus.counseling.entity.SysRole;
import com.campus.counseling.entity.SysUser;
import com.campus.counseling.entity.SysUserRole;
import com.campus.counseling.model.common.exception.ServiceException;
import com.campus.counseling.model.dto.CounselorDTO;
import com.campus.counseling.model.mapper.CounselorMapper;
import com.campus.counseling.model.mapper.SysRoleMapper;
import com.campus.counseling.model.mapper.SysUserMapper;
import com.campus.counseling.model.mapper.SysUserRoleMapper;
import com.campus.counseling.model.vo.CounselorVO;
import com.campus.counseling.service.CounselorService;
import com.campus.counseling.util.SecurityUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class CounselorServiceImpl extends ServiceImpl<CounselorMapper, Counselor> implements CounselorService {
    
    private final CounselorMapper counselorMapper;
    private final SysUserMapper userMapper;
    private final SysUserRoleMapper userRoleMapper;
    private final SysRoleMapper roleMapper;

    @Override
    public Page<CounselorVO> getCounselorList(Page<Counselor> page, CounselorDTO query) {
        // 使用新的分页查询方法
        Page<Counselor> counselorPage = counselorMapper.selectCounselorPage(page, query);
        
        // 转换为 VO
        Page<CounselorVO> voPage = new Page<>(page.getCurrent(), page.getSize(), counselorPage.getTotal());
        voPage.setRecords(counselorPage.getRecords().stream()
                .map(this::convertToVO)
                .collect(Collectors.toList()));
        return voPage;
    }

    private CounselorVO convertToVO(Counselor counselor) {
        CounselorVO vo = new CounselorVO();
        BeanUtils.copyProperties(counselor, vo);
        
        // 将逗号分隔的字符串转换为List
        if (StringUtils.hasText(counselor.getSpecialty())) {
            vo.setSpecialty(Arrays.asList(counselor.getSpecialty().split(",")));
        }
        
        return vo;
    }

    @Override
    public Page<CounselorVO> getPendingList(String status, Page<CounselorVO> page) {
        return counselorMapper.selectPendingList(page, status);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void reviewCertification(Long counselorId, String status, String reviewNote) {
        // 获取咨询师信息
        Counselor counselor = counselorMapper.selectById(counselorId);
        if (counselor == null) {
            throw new ServiceException("咨询师不存在");
        }

        // 转换状态为大写
        status = status.toUpperCase();
        
        // 验证状态值是否合法
        if (!status.equals(Counselor.STATUS_APPROVED) && 
            !status.equals(Counselor.STATUS_REJECTED)) {
            throw new ServiceException("无效的状态值");
        }

        LocalDateTime now = LocalDateTime.now();  // 添加当前时间

        // 更新审核信息
        counselor.setStatus(status);
        counselor.setReviewNote(reviewNote);
        counselor.setReviewTime(now);
        counselor.setReviewerId(SecurityUtils.getUserId());
        
        // 如果审核通过，创建用户账号
        if (Counselor.STATUS_APPROVED.equals(status)) {
            // 创建用户
            SysUser user = new SysUser();
            user.setUsername(counselor.getUsername());
            user.setPassword(counselor.getPassword());
            user.setRealName(counselor.getRealName());
            user.setPhone(counselor.getPhone());
            user.setEmail(counselor.getEmail());
            user.setStatus(1);
            user.setRole("counselor");
            user.setCreateTime(now);        // 设置创建时间
            user.setUpdateTime(now);        // 设置更新时间
            userMapper.insert(user);

            // 关联用户ID
            counselor.setUserId(user.getId());
            
            // 创建用户角色关联
            SysUserRole userRole = new SysUserRole();
            userRole.setUserId(user.getId());
            userRole.setRoleId(getRoleId("counselor"));
            userRole.setCreateTime(now);    // 设置创建时间
            userRoleMapper.insert(userRole);
        }
        
        counselorMapper.updateById(counselor);
    }

    /**
     * 根据角色标识获取角色ID
     */
    private Long getRoleId(String roleKey) {
        SysRole role = roleMapper.selectOne(
            new QueryWrapper<SysRole>()
                .eq("role_key", roleKey)
        );
        if (role == null) {
            throw new ServiceException("角色不存在: " + roleKey);
        }
        return role.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateCounselorInfo(Long id, CounselorDTO counselorDTO) {
        // 检查咨询师是否存在
        Counselor counselor = getById(id);
        if (counselor == null) {
            throw new ServiceException("咨询师不存在");
        }

        // 更新咨询师特有信息
        counselor.setTitle(counselorDTO.getTitle());
        
        // 处理专长领域
        Object specialtyObj = counselorDTO.getSpecialty();
        if (specialtyObj instanceof List) {
            @SuppressWarnings("unchecked")
            List<String> specialtyList = (List<String>) specialtyObj;
            counselor.setSpecialty(String.join(",", specialtyList));
        } else if (specialtyObj instanceof String) {
            counselor.setSpecialty((String) specialtyObj);
        } else {
            log.warn("Unexpected specialty type: {}", specialtyObj != null ? specialtyObj.getClass() : "null");
            counselor.setSpecialty(specialtyObj != null ? specialtyObj.toString() : null);
        }

        counselor.setQualification(counselorDTO.getQualification());
        counselor.setWorkYears(counselorDTO.getWorkYears());
        counselor.setIntroduction(counselorDTO.getIntroduction());
        counselor.setCertificateUrl(counselorDTO.getCertificateUrl());
        counselor.setUpdateTime(LocalDateTime.now());
        
        // 使用 ServiceImpl 的 updateById 方法
        boolean success = updateById(counselor);
        if (!success) {
            throw new ServiceException("更新失败");
        }
    }
}